<template>
  <div class="customer-event-table-container">
    <el-table
      stripe
      :data="disposeFormListViewTime(eventList, columns)"
      :highlight-current-row="false"
      header-row-class-name="common-list-table-header__v2"
      row-class-name="customer-event-table-row"
      @sort-change="sortChange"
      v-loading="loading"
      class="customer-event-table"
      v-bind="extraAttrs">
      
      <template slot="empty">
        <BaseListForNoData
          v-show="!loading"
          table-type="smallTable"
          :notice-msg="$t('common.base.tip.noData')"
        ></BaseListForNoData>
      </template>

      <el-table-column
        v-for="(column, index) in columns"
        v-if="column.show"
        :key="`${column.field}_${index}`"
        :label="column.label"
        :prop="column.field"
        :width="column.width"
        :sortable="column.sortable"
        :show-overflow-tooltip="getEventListShowTooltip(column)"
        :class-name="column.field == 'eventNo' ? 'product-event-name-superscript-td' : ''"
        :align="column.align">
        <template slot-scope="scope">
          <template v-if="column.field === 'templateId'">
            {{scope.row.templateName}}
          </template>
          <template v-else-if="column.field === 'executor'">
            <template v-if="isOpenData && scope.row.executorStaffId">
              <open-data type='userName' :openid="scope.row.executorStaffId"></open-data>
            </template>
            <template v-else>
              {{scope.row.executorName}}
            </template>
          </template>
          <template v-else-if="column.field === 'eventNo'">
            <sample-tooltip :row="scope.row">
              <template slot="content" slot-scope="{isContentTooltip}">
                <el-tooltip :content="scope.row[column.field]" placement="top" :disabled="!isContentTooltip">
                  <a v-if="allowEventViewDetail" href="#" @click="openDetail(scope.row)" class="event-link">{{scope.row[column.field]}}</a>
                  <span v-else>{{ scope.row[column.field] }}</span>
                </el-tooltip>
              </template>
            </sample-tooltip>
          </template>
          <template v-else>
            {{ $formatFormField(column, scope.row) }}
          </template>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <BaseAddOnPagination :paginationInfo="searchModel" @pageJump="jump" @sizeChange="handleSizeChange" />

  </div>
</template>

<script>
import { isOpenData, openAccurateTab } from '@src/util/platform'
import { formatDate, useFormTimezone } from 'pub-bbx-utils';
import EventStateEnum from '@model/enum/EventStateEnum';

import { getEventOfProduct } from '@src/api/ProductApi';
import { safeNewDate } from '@src/util/time';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import AuthUtil from "@src/util/auth";
import { getRootWindow } from "@src/util/dom";

export default {
  name: 'event-table',
  props: {
    shareData: {
      type: Object,
      default: () => ({})
    },
    extraAttrs: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      ...useFormTimezone(),
      isOpenData,
      eventList: [],
      columns: this.buildColumns(),
      loading: false,
      searchModel: {
        pageSize: 10,
        pageNum: 1,
        totalItems: 0,
        orderDetail: {}
      }
    }
  },
  computed: {
    productId() {
      return this.shareData.product.id;
    },
    // 查看事件详情的权限
    allowEventViewDetail() {
      let auth = {}
      try {
        const rootWindow = getRootWindow(window)
        const _initData = JSON.parse(rootWindow?._init || '{}')
        auth = _initData?.user?.auth || {}
      } catch (e) {
        console.error(e)
      }
      return AuthUtil.hasAuth(auth, 'CASE_VIEW_DETAIL')
    },
  },
  mounted() {
    this.fetchData();
  },
  methods: {
    sortChange({ prop, order, }) {
      this.searchModel.orderDetail = {
        column: prop,
        sequence: order === 'ascending' ? 'ASC' : 'DESC',
        isSystem: 1,
      };
      this.fetchData();
    },
    openDetail(row){
      if (!window.frameElement) return;

      let fromId = window.frameElement.getAttribute('id');
      // TODO: 统一id命名
      // platform.openTab({
      //   id: `eventView_${ row.id}`,
      //   title: `事件${row.eventNo}`,
      //   close: true,
      //   url: `/event/view/${row.id}`,
      //   fromId
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageEventView,
        key: row.id,
        titleKey: row.eventNo,
        fromId
      })
    },
    jump(pN) {
      this.searchModel.pageNum = pN;
      this.fetchData();
    },
    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize;
      this.searchModel.pageNum = 1;
      this.fetchData();
    },
    fetchData() {
      const {pageNum, pageSize, orderDetail, } = this.searchModel;
      const params = {
        productId: this.productId,
        pageNum,
        pageSize,
      };

      if (Object.keys(orderDetail).length) {
        params.orderDetail = orderDetail;
      }

      this.loading = true;
      getEventOfProduct(params)
        .then(res => {
          if (!res) return;
          this.eventList = res.list
            .map(event => {
              event.createTime = formatDate(safeNewDate(event.createTime), 'YYYY-MM-DD HH:mm:ss');
              event.completeTime = event.completeTime && formatDate(safeNewDate(event.completeTime), 'YYYY-MM-DD HH:mm:ss');
              event.state = EventStateEnum.getName(event.state);
              return Object.freeze(event);
            });
          this.searchModel.totalItems = res.total;

          this.loading = false;
        })
        .catch(e => console.error('fetch event caught e', e));
    },
    buildColumns() {
      return [{
        label: this.$t('product.detail.type.event.eventNo'),
        field: 'eventNo',
        show: true,
        sortable: 'custom'
      }, {
        label: this.$t('product.detail.type.event.templateId'),
        field: 'templateId',
        show: true,
        sortable: 'custom'
      }, {
        label: this.$t('product.detail.type.executor'),
        field: 'executor',
        show: true,
        sortable: 'custom'
      }, {
        label: this.$t('product.detail.type.event.state'),
        field: 'state',
        show: true,
        width: '70px',
        sortable: 'custom'
      }, {
        label: this.$t('common.base.createTime'),
        field: 'createTime',
        show: true,
        width: '150px',
        sortable: 'custom'
      }, {
        label: this.$t('common.base.completeTime'),
        field: 'completeTime',
        show: true,
        sortable: 'custom',
      }, {
        label: this.$t('product.detail.type.suggestion'),
        field: 'suggestion',
        show: true,
        sortable: 'custom',
      }]
    }
  },
}
</script>

<style lang="scss">

  .customer-event-table-container {
    padding: 16px;
    
    .event-link {
      @include fontColor();
    }
  }

  td.product-event-name-superscript-td {
    padding: 0 !important;
    & > .cell {
      padding-left: 0 !important;
    }

    & > div {
      height: 43px;
      line-height: 43px !important;
      a {
        display: inline-block;
        height: 43px;
        line-height: 43px;
      }
    }
  }
</style>